package com.computer.mvcframework.servlet;

import com.computer.spring.framework.annotation.BYAutowired;
import com.computer.spring.framework.annotation.BYController;
import com.computer.spring.framework.annotation.BYRequestMapping;
import com.computer.spring.framework.annotation.BYService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 28761
 */
public class BYDispatcherServletMVC extends HttpServlet {

    /**
     * 保存 application.properties 配置文件中的内容
     */
    private Properties contextConfig = new Properties();

    /**
     * 保存扫描的所有类名
     */
    private List<String> classNames = new ArrayList<>();

    /**
     * ioc容器
     */
    private Map<String, Object> ioc = new HashMap<>();

    /**
     * 保存 url 和 method 的对应关系
     */
    private List<Handler> handlerMapping = new ArrayList<>();
//    private Map<String, Method> handlerMapping = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception" + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception{

        //  6、等待请求阶段
        Handler handler = getHandler(req);
        if (null == handler){
            resp.getWriter().write("404 Not Found!!!");
            return;
        }
        Class<?>[] paramTypes = handler.method.getParameterTypes();
        Object[] paramValues = new Object[paramTypes.length];

        Map<String, String[]> params = req.getParameterMap();
        for (Map.Entry<String, String[]> param : params.entrySet()){
            String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll("\\s", ",");
            if (!handler.paramIndexMapping.containsKey(param.getKey())){
                continue;
            }
            int index = handler.paramIndexMapping.get(param.getKey());
            paramValues[index] = convert(paramTypes[index], value);
        }

        if (handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())){
            int reqIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[reqIndex] = resp;
        }

        Object returnValue = handler.method.invoke(handler.controller, paramValues);
        if (null == returnValue || returnValue instanceof  Void){
            return;
        }
        resp.getWriter().write(returnValue.toString());

//        if (!this.handlerMapping.containsKey(url)){
//
//        }

//        Method method = this.handlerMapping.get(url);
//        Map<String, String[]> params = req.getParameterMap();
//        String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());
//
//        method.invoke(ioc.get(beanName), new Object[]{req, resp, params.get("name")[0]});
//        method.invoke(this.handlerMapping.get(method.getDeclaringClass().getName()), new Object[]{req, resp, params.get("name")[0]});

//        System.out.println(method);
    }

    private Object convert(Class<?> paramType, String value) {
        if (Integer.class == paramType){
            return Integer.valueOf(value);
        }
        return value;
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()){
            return null;
        }
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        for (Handler handler : handlerMapping){
            Matcher matcher = handler.pattern.matcher(url);
            if (!matcher.matches()){
                continue;
            }
            return handler;
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

//        1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        
//        2、扫描所有相关联的类
        doScanner(contextConfig.getProperty("scanPackage"));
        
//        3、初始化所有相关联的类，并且将其保存到IOC容器之中
        doInstance();
        
//        4、执行依赖注入（把加了@Autowired注解的字段赋值）
        doAutowired();
        //=============================  Spring 的核心功能已经完成 IOC、DI  ===========================================
        
//        5、构造HandlerMapping，将URL和Method进行关联
        initHandlerMapping();
        
    }

    private void initHandlerMapping() {

        if (ioc.isEmpty()){
            return;
        }

        for (Map.Entry<String, Object> entry: ioc.entrySet()){

            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(BYController.class)){
                continue;
            }
            String baseUrl = "";
            if (clazz.isAnnotationPresent(BYRequestMapping.class)){
                BYRequestMapping requestMapping = clazz.getAnnotation(BYRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            Method [] methods = clazz.getMethods();
            for (int i = 0; i < methods.length; i++){
                Method method = methods[i];

                if (!method.isAnnotationPresent(BYRequestMapping.class)){
                    continue;
                }
                BYRequestMapping requestMapping = method.getAnnotation(BYRequestMapping.class);
                String regex = ("/" + baseUrl + requestMapping.value()).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                handlerMapping.add(new Handler(entry.getValue(), method, pattern));

//                String url = requestMapping.value();
//
//                url = (baseUrl + url).replaceAll("/+", "/" );
//                handlerMapping.put(url, method);
//
//                System.out.println("Mapping : " + url + "," + method);
            }
        }
    }

    private void doAutowired() {

        if (ioc.isEmpty()){
            return;
        }

        for (Map.Entry<String, Object> entry: ioc.entrySet()){

            //  注入的意思就是把所有的IOC容器中加了@Autowired注解的字段全部赋值
            //  包括私有的字段
            Field[] fields = entry.getValue().getClass().getDeclaredFields();

            for (Field field : fields){
                //  判断是否加了注解
                if (!field.isAnnotationPresent(BYAutowired.class)){
                    continue;
                }

                BYAutowired autowired = field.getAnnotation(BYAutowired.class);
                String beanName = autowired.value().trim();

                if ("".equals(beanName)){
                    beanName = field.getType().getName();
                }

                //  如果这个字段是私有字段的话，那么，要强制访问
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    private void doInstance() {

        if (classNames.isEmpty()){
            return;
        }

        try {
            for (String className : classNames){
                Class<?> clazz = Class.forName(className);

                /**
                 * ioc.put()
                 * key的规则
                 * 1、默认类名首字母小写
                 * <bean id="xxx" class="xxx"
                 * 2、自定义命名，优先使用自定义命名
                 * 3、自动类型匹配（例如：将实现类赋值给接口）
                 */
                if (clazz.isAnnotationPresent(BYController.class)){
                    Object instance = clazz.newInstance();
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName, instance);
                }else if(clazz.isAnnotationPresent(BYService.class)){
//                    Service
                    BYService service = clazz.getAnnotation(BYService.class);
                    //  2、自定义命名，优先使用自定义命名
                    String beanName = service.value();

                    //  1、默认类名首字母小写
                    if ("".equals(beanName.trim())){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);

                    //  3、自动类型匹配（例如：将实现类赋值给接口）
                    Class<?> [] interfaces = clazz.getInterfaces();
                    for (Class<?> i : interfaces){
                        if (ioc.containsKey(i.getName())){
                            throw new Exception("the “" + i.getName() + "“ is exists!!!");
                        }
                        ioc.put(i.getName(), instance);
                    }
                }else{
                    continue;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String lowerFirstCase(String str) {
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private void doScanner(String basePackage) {

        URL url = this.getClass().getClassLoader().getResource("/"+basePackage.replaceAll("\\.", "/"));
        File dir = new File(url.getFile());
        for (File file : dir.listFiles()){
            if (file.isDirectory()){
                doScanner(basePackage + "." + file.getName());
            }else{
                if (!file.getName().endsWith(".class")){
                    continue;
                }
                String className = basePackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
//                System.out.println(className);
            }
        }

    }

    private void doLoadConfig(String location) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location);

        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
